<?php

function _cck_timed_publishing_cron()
{
  $result = db_query("SELECT content_type, publish_field, unpublish_field
    FROM {cck_timed_publishing} 
    WHERE enabled=1");
  while ($settings = db_fetch_object($result)) {
    $publish_field = content_fields($settings->publish_field,$settings->content_type);
    $db = content_database_info($publish_field);
    
    $ntp_results = db_query("SELECT n.nid
      FROM {node} AS n
        INNER JOIN {{$db['table']}} AS ft ON ft.nid=n.nid
      WHERE n.status = 0 
      AND n.type = '%s'
      AND ft.{$db['columns']['value']['column']}<%d
      LIMIT 20", array($settings->content_type, time()));
    
    while ($node_to_publish = db_fetch_object($ntp_results)) {
      $node = node_load($node_to_publish);
      $arguments = array('node' => $node);
      $node->status = 1;
      if (module_exists('workflow_ng')) {
        workflow_ng_invoke_event('cck_timed_publishing_node_published', $arguments);
      }
      node_save($node);
    }
  }
}

function _cck_timed_publishing_service() {
  return array(
    array(
      '#method' => 'timed_publishing.interval',
      '#callback' => 'cck_timed_publishing_last_published',
      '#args' => array(
        array(
          '#name' => 'from',
          '#type' => 'string',
          '#optional' => false,
          '#description' => t('A from date and time to get nodes from'),
        ),
        array(
          '#name' => 'to',
          '#type' => 'string',
          '#optional' => false,
          '#description' => t('A to date and time to get nodes to'),
        ),
        array(
          '#name' => 'type',
          '#type' => 'string',
          '#optional' => false,
          '#description' => t('The node types to get'),
        ),
        array(
          '#name' => 'fields',
          '#type' => 'array',
          '#optional' => true,
          '#description' => t('A list of fields to filter.'),
        ),
        array(
          '#name' => 'filters',
          '#type' => 'array',
          '#optional' => true,
          '#description' => t('An array or JSON-specification of field filters to run".'),
        ),
      ),
      '#return' => 'array',
      '#help' => 'Returns a list of nodes'
    )
  );
}

function _cck_timed_publishing_last_published($from,$to,$content_type,$fields=Null,$filters=array())
{ 
  if (!user_access('preview timed publishing')) {
    return false;
  }  
  
  $from = strtotime($from);
  $to = strtotime($to);
  
  $field = cck_timed_publishing_get_time_field($content_type);
  $publish_field = preg_replace('/_value$/','',$field['field']);
  
  //Make sure that we have the required field if fields are set
  if (isset($fields)) {
    $required_fields = array('nid', $publish_field, 'title');
    foreach ($required_fields as $rfield) {
      if (!in_array($rfield,$fields)) {
        array_unshift($fields, $rfield);
      }
    }
  }

  $filters = node_field_filters_parse($filters);
  
  $res = db_query("SELECT cct.nid, cct.{$field['field']} AS published 
    FROM {{$field['table']}} AS cct
      INNER JOIN {node} AS n ON n.vid = cct.vid
    WHERE cct.{$field['field']} >= %d 
    AND cct.{$field['field']} <= %d
    AND n.status = 0
    AND n.type = '%s'
    ORDER BY cct.{$field['field']} ASC",
    $from, $to, $content_type);
  $nodes = array();
  while ($node = db_fetch_object($res)) {
    $node = node_load($node->nid);
    if(is_array($fields)) {
      $node = services_node_load($node, $fields);
    }
    
    //Apply filters
    node_field_filters_apply($node,$filters);
    
    $nodes[] = $node;
  }
  return $nodes;
}

function _cck_timed_publishing_menu(&$items)
{
  $items[] = array(
    'path' => 'admin/content/timed_publishing',
    'title' => t('Timed publishing'),
    'callback' => 'cck_timed_publishing_admin',
    'access' => user_access('administer timed publishing'),
    'type' => MENU_NORMAL_ITEM,
  );

  $types = content_types();
  $content_types = array();
  foreach($types as $name => $def)
  {
    $items[] = array(
      'path' => 'admin/content/timed_publishing/'. $name,
      'title' => $def['name'],
      'callback' => 'drupal_get_form',
      'callback arguments' => array('cck_timed_publishing_admin_content_type',$name),
      'access' => user_access('administer timed publishing'),
      'type' => MENU_NORMAL_ITEM,
    );
  }
  
  return $items;
}

function _cck_timed_publishing_admin_content_type($content_type)
{
  $form = array();
  
  $settings = cck_timed_publishing_settings($content_type);
  $fields = cck_timed_publishing_date_fields($content_type);
  
  $form['enabled'] = array(
    '#type' => 'checkbox', 
    '#title' => t('Use scheduled publishing'),
    '#default_value' => $settings->enabled,
  );
  
  $form['publish_field'] = array(
    '#type' => 'select', 
    '#title' => t('Select a field that contains the publishing dates'), 
    '#default_value' => $settings->publish_field,
    '#options' => array(''=>t('-- Select a field')) + $fields,
    '#description' => t('The selected field will be used to determine when a node will be published'),
  );
  
  $form['unpublish_field'] = array(
    '#type' => 'select', 
    '#title' => t('Select a field that contains the unpublishing dates'), 
    '#default_value' => $settings->unpublish_field,
    '#options' => array(''=>t('-- Select a field')) + $fields,
    '#description' => t('The selected field will be used to determine when a node will be unpublished'),
  );
  
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
  
  return $form;
}

function cck_timed_publishing_admin_content_type_validate($form_id, $form_values) {
  if (!empty($form_values['publish_field']) && $form_values['publish_field'] == $form_values['unpublish_field']) {
    form_set_error('unpublish_field', t('You cannot set publish and upublish to the same fields.'));
  }
}

function cck_timed_publishing_admin_content_type_submit($form_id, $form_values) {
  cck_timed_publishing_update_settings(arg(3), $form_values['publish_field'], $form_values['unpublish_field'], $form_values['enabled']);
  drupal_set_message(t('Your settings have been saved.'));
}

function _cck_timed_publishing_admin() {
  $types = content_types();
  $output = '<ul>';
  foreach($types as $name => $def)
    $output .= '<li>'.l($def['name'], 'admin/content/timed_publishing/'. $name).'</li>';
  $output .= '</ul>';
  return $output;
}